package com.food.chain.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.food.chain.common.jwt.Jwt;
import com.food.chain.common.util.EncryptUtil;
import com.food.chain.common.util.ExcelUtil;
import com.food.chain.common.util.IpUtil;
import com.food.chain.common.util.PropertyUtil;
import com.food.chain.constant.Constant;
import com.food.chain.dao.StudentInterfaceDao;
import com.food.chain.dao.UserDao;
import com.food.chain.entity.User;

@Service
@Transactional
public class UserService {
	private static final SimpleDateFormat format_file = new SimpleDateFormat("yyyyMMddHHmmss");
	@Autowired
	private StudentInterfaceDao studentDao;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private HttpServletResponse response;
	
	@Autowired
	private HttpServletRequest request;
	
	/**
	 * 用户登录
	 * @param jsonString
	 * @return
	 */
	public JSONObject userLogin(String jsonString) throws Exception{
		JSONObject result = new JSONObject();
		
		JSONObject object = JSONObject.parseObject(jsonString);
		
		if (object == null || object.isEmpty()) {
			result.put("success", false);
			result.put("message", "请输入用户名和密码");
		}else {
			Map<String, Object> param = new HashMap<>();
			param.put("userID", object.get("userId"));
			String pwd = "";
			if (object.get("password") != null) {
				pwd = object.get("password").toString();
			}
			// 获取用户信息
			Map<String, Object> userMap = userDao.getUserInfo(object.get("userId").toString());
			
			String password = userMap.get("U_Pwd").toString();
			// 密码check
			if (BCrypt.checkpw(EncryptUtil.SHA512(pwd), password)) {
				// token做成
				Map<String , Object> payload = new HashMap<String, Object>();
				Date date = new Date();
				payload.put("u_id", object.get("userId"));//用户ID
				payload.put("u_name", userMap.get("U_Name").toString());//用户名
				payload.put("u_role", userMap.get("U_Role").toString());//用户角色
				payload.put("isadmin", userMap.get("IsAdmin").toString());//是否管理员
				payload.put("u_avatar", userMap.get("U_Avatar").toString());//用户头像
				payload.put("iat", date.getTime());//生成时间
				payload.put("exp", date.getTime() + 1000*60*60*24*7);//过期时间7天
				String token = Jwt.createToken(payload);
				
				// 更新用户登陆时间和ip
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("userID", object.get("userId"));
				paramMap.put("ip", IpUtil.getRemortIP(request));
				userDao.updateUserLoginIP(paramMap);
				
				//设置cookie
				Cookie cookie = new Cookie("token", token);
				cookie.setMaxAge(60*60*24*7);//设置cookie过期时间7天
				cookie.setPath("/");
				response.addCookie(cookie);
				
				// 获取跳转的画面
				String redirect = PropertyUtil.getProperty("userIndex");;
				
				result.put("success", true);
				result.put("message", "登陆成功");
				result.put("redirect", redirect);
				result.put("u_id", object.get("userId"));//用户ID
				result.put("U_Pwd", password);//用户ID
				result.put("role", userMap.get("U_Role").toString());//用户角色
			}else {
				result.put("success", false);
				result.put("message", "用户名或密码不正确");
			}
		}
		
		return result;
	}
	
	
	/**
	 * 修改密码
	 * @throws Exception
	 */
	public JSONObject changePwd(String oldpwd, String newpwd) throws Exception {
		JSONObject returnMap = new JSONObject();
		
//		@SuppressWarnings("unchecked")
//		Map<String, Object> uMap = (Map<String, Object>) request.getAttribute("user_info");
//		Map<String, Object> param = new HashMap<>();
//		param.put("userID", uMap.get("u_id"));
		
		// 获取登录信息
		Subject currentUser = SecurityUtils.getSubject();
		Map<String, Object> userMap = null;
		if (currentUser != null) {
			userMap = userDao.getUserInfo(currentUser.getPrincipal().toString()); //获取用户信息
		}
		
		if(userMap != null && userMap.size() != 0) {
			if (Constant.USRE_VALIDE.equals(userMap.get("DelFlag").toString())) {//有效用户
				String password = userMap.get("U_Pwd").toString();
				if (BCrypt.checkpw(EncryptUtil.SHA512(oldpwd), password)){ //校验原密码
					userMap.put("U_Pwd", BCrypt.hashpw(EncryptUtil.SHA512(newpwd), BCrypt.gensalt()));//加密新密码
					// 更新用户密码
					userDao.updateUserPwd(userMap);
					returnMap.put("success", true);
					returnMap.put("msg", "修改成功");
				}else{
					returnMap.put("success", false);
					returnMap.put("msg", "旧密码错误");
				}
			}else{
				returnMap.put("success", false);
				returnMap.put("msg", "用户已删除");
			}
		}else{
			returnMap.put("success", false);
			returnMap.put("msg", "用户不存在");
		}
		
		return returnMap;
	}
	
	
	/**
	 * 获取用户列表
	 * @param jsonString
	 * @return
	 */
	public Map<String, Object> GetUserList(String jsonString) {
		Map<String, Object> result = new HashMap<>();
		boolean success = true;
		try {
			JSONObject object = JSONObject.parseObject(jsonString);
			// 获取每页记录
			List<Map<String, Object>> users = studentDao.getUser(object);
			// 获取总数
			int count = studentDao.getNumberOfAllUser(object);
			
			// Pagination必须设置 rows,total这两属性,
			// 因为loadFilter函数要求必须返回标准数据对象，含有 'total' 和 'rows' 属性。
			result.put("rows", users); // 此参数必须是rows,存放每页记录数
			result.put("total", count); // 存放总数
		} catch (Exception e) {
			success = false;
			throw e;
		}
		
		result.put("success", success);
		
		return result;
	}
	
	public int addUser(User user) throws Exception {
		System.out.println("添加用户");
		return studentDao.saveUser(user);
		//throw new RuntimeException();
		//throw new Exception();
	}
	
	
	/**
	 * 导出
	 * @param jsonString
	 */
	public void exportUserInfo(String jsonString, HttpServletResponse response) throws Exception{
		JSONObject object = JSONObject.parseObject(jsonString);
		
		String fileName = "用户列表", sheetName = "用户列表";

	    fileName = fileName +"_"+ format_file.format(new Date()) + ".xls";
		List<Map<String, Object>> list = null;
		list = studentDao.getUserExportList(object);
		// 表头
		String[] titleStr = new String[] { "姓名", "密码", "邮箱","状态" };
		// 与表头对应的bean属性
		String[] keys = new String[] { "userName", "password", "emailAddress", "isDelete"};
		
		// 导出文件
		ExcelUtil.exportExcelData(fileName, sheetName, titleStr, list, keys, response);
	}
	
	/**
	 * 导出
	 * @param jsonString
	 */
	public Map<String, Object> exportUserInfoList(String jsonString) throws Exception{
		Map<String, Object> result = new HashMap<>();
		boolean success = true;
		try {
			JSONObject object = JSONObject.parseObject(jsonString);
			List<Map<String, Object>> list = null;
			list = studentDao.getUserExportList(object);
			
			result.put("data", list);
		} catch (Exception e) {
			success = false;
			throw e;
		}
		
		result.put("success", success);
		
		return result;
	}
	
	/**
	 * 更新登录的IP地址
	 * @param userId
	 * @param strIP
	 */
	public void updateUserLoginIP(String userId) {
		// 更新用户登陆时间和ip
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userID", userId);
		String strIP = IpUtil.getRemortIP(request);
		paramMap.put("ip", "127.0.0.1");
		userDao.updateUserLoginIP(paramMap);
	}
	
	
}
